import 'dart:isolate';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
import 'package:get/get.dart';
import '../logs/Logger.dart';


class TranslationOverLay3 extends StatefulWidget {
  @override
  State<TranslationOverLay3> createState() => TranslationOverLayState();
}

class TranslationOverLayState extends State<TranslationOverLay3> {

  static const String _mainAppPort = 'MainApp';
  SendPort? mainAppPort;
  bool update = false;


  final _receivePort = ReceivePort();
  SendPort? homePort;
  String? latestMessageFromOverlay;

  String finalFromLanguage = '';
  String finalToLanguage = '';



  ScrollController scrollControllerTop = ScrollController();
  ScrollController scrollControllerBottom = ScrollController();

  @override
  void initState() {
    super.initState();

    if (homePort != null) return;

    final res = IsolateNameServer.registerPortWithName(
      _receivePort.sendPort,
      _mainAppPort,
    );

    logger.info("$res: OVERLAY");


    _receivePort.listen((message) async {
      logger.info("message from OVERLAY: $message");
      print('OverLay refresh ... 1 ');

      // await SystemAlertWindow.sendMessageToOverlay(message);
      print('OverLay refresh ... 2 ');



      print('OverLay finalFromLanguage : ${finalFromLanguage}, finalToLanguage: ${finalToLanguage}');


    });


    /*SystemAlertWindow.overlayListener.listen((message) {
      logger.info("$message in overlay");
      setState(() {
        finalFromLanguage = message['finalFromLanguage'];
        finalToLanguage = message['finalToLanguage'];
        // 延迟到下一帧执行，确保布局完成
        SchedulerBinding.instance.addPostFrameCallback((_) {
          _autoScrollToTop();
          // _autoScrollToBottom();
        });
      });
    });*/


    FlutterOverlayWindow.overlayListener.listen((message) {
      print("FlutterOverlayWindow Event: $message");
      setState(() {
        finalFromLanguage = message['finalFromLanguage']??'';
        finalToLanguage = message['finalToLanguage']??'';
        // 延迟到下一帧执行，确保布局完成
        SchedulerBinding.instance.addPostFrameCallback((_) {
          _autoScrollToTop();
          // _autoScrollToBottom();
        });
      });

    });

  }

  void _autoScrollToTop() {
    // 使用 animateTo 实现平滑滚动
    if(finalFromLanguage.trim() != '') {
      scrollControllerTop.animateTo(
          scrollControllerTop.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut
      );
    }

    if(finalToLanguage.trim() != '') {
      scrollControllerBottom.animateTo(
          scrollControllerBottom.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut
      );
    }

  }

  void callBackFunction(String tag) {
    print("Got tag " + tag);
    mainAppPort ??= IsolateNameServer.lookupPortByName(
      _mainAppPort,
    );
    mainAppPort?.send('Date: ${DateTime.now()}');
    mainAppPort?.send(tag);
  }

  @override
  Widget build(BuildContext context) {
    print('OverLay refresh ... 3 ');
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: overlay(),
    );
  }


  Widget overlay() {
    return Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      // margin: EdgeInsets.all(20),
      padding: EdgeInsets.only(right: 10,left: 10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: Colors.black
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              InkWell(
                child: Container(
                    margin: EdgeInsets.only(left: 10,top: 10),
                    child: Image.asset('assets/images/icon_float_window_close.png',width: 16,height: 16)
                ),
                onTap: () async {
                  await FlutterOverlayWindow.closeOverlay();
                },
              ),
              InkWell(
                onTap: () async {
                  await FlutterOverlayWindow.lanchMainActivity();
                  await FlutterOverlayWindow.closeOverlay();
                },
                child: Container(
                  margin: EdgeInsets.only(right: 10,top: 10),
                  child: Image.asset('assets/images/icon_float_window_reback.png',width: 16,height: 16),
                  padding: EdgeInsets.all(5),
                ),
              )
            ],
          ),
          Container(
            height: MediaQuery.of(context).size.height == 0 ? 0 : MediaQuery.of(context).size.height-40,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                finalFromLanguage.trim() != '' ? Expanded(child: Container(
                  padding: EdgeInsets.only(right: 10,left: 10),
                  width: MediaQuery.of(context).size.width,
                  child: SingleChildScrollView(
                    padding: EdgeInsets.only(bottom: 10),
                    controller: scrollControllerTop,
                    child: finalFromLanguage.trim() != '' ?  Text(finalFromLanguage.trim(), style: TextStyle(
                        color: Colors.white)
                    ):
                    Text('正在处理,请稍后 ...',style: TextStyle(
                        color: Colors.white
                    ),),
                  ),
                ),flex: 1,) : SizedBox(),
                (finalFromLanguage.trim() != '' && finalToLanguage.trim() != '') ? Container(
                  decoration: BoxDecoration(
                      color: Colors.white30,
                      borderRadius:BorderRadius.all(Radius.circular(10))
                  ),
                  child: SizedBox(width: MediaQuery.of(context).size.width, height: 1),
                ): SizedBox(),
                finalToLanguage.trim() != '' ? Expanded(child: Container(
                  margin: EdgeInsets.only(top: 5),
                  padding: EdgeInsets.only(right: 10,left: 10),
                  width: MediaQuery.of(context).size.width,
                  child: SingleChildScrollView(
                    padding: EdgeInsets.only(bottom: 10),
                    controller: scrollControllerBottom,
                    child: finalToLanguage.trim() != '' ?  Text(finalToLanguage.trim(),style: TextStyle(
                        color: Colors.white)
                    ):
                    Text('',style: TextStyle(
                        color: Colors.white
                    ),),
                  ),
                ),flex: 1,):SizedBox()
              ],
            ),
          )
        ],
      )/*Stack(
        children: [
          Positioned(child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(child: Container(
                padding: EdgeInsets.only(right: 10,left: 10),
                width: MediaQuery.of(context).size.width,
                child: SingleChildScrollView(
                  padding: EdgeInsets.only(bottom: 10),
                  controller: scrollControllerTop,
                  child: finalFromLanguage.trim() != '' ?  Text(finalFromLanguage, style: TextStyle(
                      color: Colors.white)
                  ):
                  Text('正在处理,请稍后 ...',style: TextStyle(
                      color: Colors.white
                  ),),
                ),
              ),flex: 1,),
              Container(
                decoration: BoxDecoration(
                    color: Colors.white54,
                    borderRadius:BorderRadius.all(Radius.circular(10))
                ),
                child: SizedBox(width: MediaQuery.of(context).size.width, height: 1),
              ),
              Expanded(child: Container(
                padding: EdgeInsets.only(right: 10,left: 10),
                width: MediaQuery.of(context).size.width,
                child: SingleChildScrollView(
                  padding: EdgeInsets.only(bottom: 10),
                  controller: scrollControllerBottom,
                  child: finalFromLanguage.trim() != '' ?  Text(finalToLanguage,style: TextStyle(
                      color: Colors.white)
                  ):
                  Text('',style: TextStyle(
                      color: Colors.white
                  ),),
                ),
              ),flex: 1,)
            ],
          ),top: 25),
          Positioned(child: GestureDetector(
              onTap: () async {
                await FlutterOverlayWindow.closeOverlay();
                  // SystemAlertWindow.closeSystemWindow();
              },
              child: Container(
                child: Image.asset('assets/images/icon_float_window_close.png',width: 16,height: 16)
              ),
          ),
          top: 10, left: 10,),
          Positioned(child: GestureDetector(
            onTap: () async {
              await FlutterOverlayWindow.lanchMainActivity();
              await FlutterOverlayWindow.closeOverlay();
            },
            child: Container(
              child: Image.asset('assets/images/icon_float_window_reback.png',width: 16,height: 16),
              padding: EdgeInsets.all(5),
            ),
          ),
            top: 10, right: 10,)
        ],
      )*/,
    );
  }
  
}